<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item><i class="el-icon-lx-warn"></i>&nbsp;&nbsp;一个管理员可以有多个角色组,左侧的菜单根据管理员所拥有的权限进行生成</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
           <div class="table_btn">
               <el-button type="success" icon="el-icon-edit" @click="addUser($event)">添加</el-button>
               <el-button type="danger" icon="el-icon-delete"  @click="allDelete()">批量删除</el-button>
               <el-input v-model="query.keywords"  placeholder="用户名" class="menu-input" clearable></el-input>
               <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
           </div>
           <div class="box_table">
                <el-table
                        :data="tableData"
                        border
                        @selection-change="handleSelectionChange"
                        style="width: 100%">
                    <el-table-column
                            type="selection"
                            width="55">
                    </el-table-column>
                    <el-table-column
                            prop="id"
                            label="序号"
                            width="80">
                    </el-table-column>
                    <el-table-column
                            prop="user"
                            label="用户名"
                            width="180">
                    </el-table-column>
                    <el-table-column
                            prop="nickname"
                            label="昵称"
                            width="180">
                    </el-table-column>
                    <el-table-column
                        prop="group"
                        label="所属组别">

                        <template slot-scope="scope">
                            <el-tag type="primary"
                                    class="group-tap"
                                    v-for="(v,i) in scope.row.group"
                                    disable-transitions>{{v[1]}}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column
                            prop="email"
                            label="Email">
                    </el-table-column>
                    <el-table-column
                            prop="status"
                            label="状态"
                            width="100"
                            :filters="[{ text: '正常', value: '正常' }, { text: '禁用', value: '禁用' }]"
                            :filter-method="filterTag"
                            filter-placement="bottom-end">
                        <template slot-scope="scope">
                            <el-tag
                                    :type="scope.row.status === 1 ? 'primary' : 'success'"
                                    disable-transitions>{{scope.row.status===1?'正常':'禁用'}}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column
                            prop="last_login"
                            label="最后登录">
                    </el-table-column>
                    <el-table-column label="操作" width="200">
                        <template slot-scope="scope">
                            <el-button
                                    size="mini"
                                    icon="el-icon-edit"
                                    type="primary"
                                    @click="handleEdit(scope.$index, scope.row)">
                                编辑
                            </el-button>
                            <el-button
                                    size="mini"
                                    type="danger"
                                    icon="el-icon-delete"
                                    @click="handleDelete(scope.$index, scope.row)">
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
           <div class="pagination">
                <el-pagination
                        background
                        layout="total, prev, pager, next"
                        :total="pageTotal"
                        :current-page.sync="currentPage"
                        :page-size="pageSize"
                        @current-change="handlePageChange"
                ></el-pagination>
           </div>
        </div>

        <!--添加-->
        <el-dialog title="添加管理员" :visible.sync="dialogFormVisible"  width="35%">
            <el-form :model="form" :rules="rules" ref="form" label-width="100px">

                <el-form-item label="所属组别" prop="group">
                    <el-select
                        v-model="form.group"
                        placeholder="请选择"
                        multiple
                        collapse-tags
                    >
                        <el-option
                            v-for="item in groupOpt"
                            :key="item.id"
                            :label="item.title_show"
                            :value="item.id">
                        </el-option>
                    </el-select>

                </el-form-item>

                <el-form-item label="用户名" prop="user">
                    <el-input v-model="form.user"></el-input>
                </el-form-item>
                <el-form-item label="昵称" prop="nickname">
                    <el-input v-model="form.nickname"></el-input>
                </el-form-item>
                <el-form-item label="email" prop="email">
                    <el-input v-model="form.email"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="form.mobile"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="form.password" show-password></el-input>
                </el-form-item>
                <el-form-item label="状态">
                    <el-switch v-model="form.status"
                               active-text="正常"
                               inactive-text="隐藏"
                               :active-value="1"
                               :inactive-value="0"
                    ></el-switch>
                </el-form-item>
                <el-form-item>
                    <el-button
                            type="primary"
                            @click="submitForm('form')"
                            :loading="addUserLoading"
                    >立即创建</el-button>
                    <el-button @click="resetForm('form')">重置</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

        <!-- 编辑 -->
        <el-dialog title="编辑管理员信息" :visible.sync="editDialog"  width="35%">
            <el-form :model="currentEditData"
                     :rules="editRules"
                     ref="edit_form"
                     label-width="100px">

                <el-form-item label="所属组别" prop="group">
                    <el-select
                        v-model="currentEditData.group_ids"
                        placeholder="请选择"
                        multiple
                        collapse-tags
                    >
                        <el-option
                                v-for="item in groupOpt"
                                :key="item.id"
                                :label="item.title_show"
                                :value="item.id">
                        </el-option>
                    </el-select>

                </el-form-item>

                <el-form-item label="用户名" prop="user">
                    <el-input v-model="currentEditData.user"></el-input>
                </el-form-item>
                <el-form-item label="昵称" prop="nickname">
                    <el-input v-model="currentEditData.nickname"></el-input>
                </el-form-item>
                <el-form-item label="email" prop="email">
                    <el-input v-model="currentEditData.email"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="currentEditData.mobile"></el-input>
                </el-form-item>

                <el-form-item label="密码" prop="password">
                    <el-input v-model="currentEditData.password"
                              placeholder="留空则不修改密码"
                              show-password
                    ></el-input>
                </el-form-item>

                <el-form-item label="状态">
                    <el-switch v-model="currentEditData.status"
                               active-text="正常"
                               inactive-text="隐藏"
                               :active-value="1"
                               :inactive-value="0">

                    </el-switch>
                </el-form-item>

                <el-form-item>
                    <el-button
                            type="primary"
                            @click="edit('edit_form')"
                            :loading="editUserLoading"
                    >修 改</el-button>
                    <el-button @click="resetForm('edit_form')">重置</el-button>
                </el-form-item>

            </el-form>
        </el-dialog>

    </div>
</template>
<script>

    import utils  from "@/utils/function"
    const  { request,checkMobile,dateFormat } = utils
    import Paging from "@/utils/paging"
    const paging = new Paging("/system/auth/user-list")

    export default {
        data() {
            //验证规则
            let addRules = {
                group:[
                    { required: true, message: '请选择组别', trigger: 'change' }
                ],
                user: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
                ],
                nickname: [
                    { required: true, message: '请输入昵称', trigger: 'blur' },
                    { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ],
                email: [
                    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
                ],
                mobile: [
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    {
                        validator: (rule, value, callback)=>{
                            if( !checkMobile(value) ){
                                callback(new Error('请输入正确的手机号'));
                            } else {
                                callback();
                            }
                        },
                        message: '请输入正确的手机号',
                        trigger: ['blur', 'change']
                    }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' }
                ]
            }
            let editRules = {
                group_ids:addRules.group,
                user:addRules.user,
                nickname:addRules.nickname,
                email: addRules.email,
                mobile:addRules.mobile
            };
            return {
                tableData: [],
                pageTotal: 0,
                multipleSelection:[],           //列表中checkbox选中的值
                dialogFormVisible:false,        //新增界面的显示
                query: {                        //查询数据
                    keywords:""
                },
                currentPage:1,
                pageSize:5,
                form: {
                    group: [],
                    user: '',
                    nickname: '',
                    email: '',
                    password: '',
                    status:'',
                    mobile:''
                },
                groupOpt:[],            //角色组
                rules: addRules,
                editRules:editRules,
                currentEditData:{
                    id:0,
                    user:'',
                    mobile:'',
                    nickname:'',
                    status:0,
                    email:'',
                    password:'',
                    group_ids:[]
                },     //当前编辑数据
                editDialog:false,        //编辑界面的显示
                addUserLoading:false,
                editUserLoading:false,
            }
        },
        created() {
            this.getUserList({page:1})
            //获取角色数据
            request.get("/system/auth/add-user").then(response=>{
                let {code,data:{roleList},msg} = response
                if(code === 0){
                    this.groupOpt = roleList
                }
            }).catch(error=>{
                console.log(error);
            });
        },
        methods: {
            handlePageChange(val) {             //获取分页数据
                this.getUserList({page:val})
            },
            handleSearch(){             //查询
                paging.setQuery( _.cloneDeep(this.query) );
                this.handlePageChange(1)
                this.currentPage = 1
            },

            getUserList({page,keywords}){           //获取列表数据
                paging.request({page,keywords}).then(response=>{
                    let {code,data:{currentPage,total,userList},msg} = response
                    if(code === 0){
                        this.pageTotal = total;

                        if(_.isArray(userList) && userList.length > 0){
                            this.tableData = userList.map((value)=>{
                                return {
                                    id:value.id,
                                    user: value.user_name,
                                    nickname: value.user_nickname,
                                    group: _.map(value.roleInfo,(item,key)=>[key,item]),
                                    group_ids:_.map(value.roleInfo,(item,key)=>parseInt(key)),
                                    email: value.user_email,
                                    status: value.user_status,
                                    last_login: value.last_login_time ? dateFormat(value.last_login_time):'',
                                    mobile:value.mobile
                                }
                            })
                        } else {
                            this.tableData = []
                        }

                    } else {
                        this.$message.error(msg);
                    }
                }).catch(error=>{
                    console.log(error);
                });
            },
            clearFilter() {
                this.$refs.filterTable.clearFilter();
            },
            filterTag(value, row) {
                return row.status === value;
            },
            handleSelectionChange(val) {        //列表中checkbox选中事件

                this.multipleSelection = val;
            },
            delete(ids){                        //删除管理员数据
                this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    if(_.isNumber(ids)){
                       ids = [ids]
                    }
                    if(!_.isArray(ids)){
                        return false;
                    }
                    request.post("/system/auth/delete-admin",{ids}).then(response=>{
                        console.log(response);
                        let {code,data,msg} = response
                        if(code === 0){
                            this.getUserList({page:this.currentPage})
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                        } else {
                            this.$message.error(msg);
                        }
                    }).catch(error=>{
                        console.log(error);
                    });

                }).catch((error) => {
                    console.log(error);
                    this.$message({
                        type: 'info',
                        message: '删除失败，请重试!'
                    });
                });
            },
            handleDelete(index,item){           //删除一条

                this.delete(item.id);
            },
            allDelete(){                    //批量删除
                if(this.multipleSelection.length<1){
                    this.$message.error('选择要删除的内容');
                    return ;
                }
                this.delete(this.multipleSelection.map(value => value.id))
            },
            addUser(){                      //显示添加管理员界面
                this.dialogFormVisible = true
            },
            submitForm(form) {          //新增管理员提交
                this.$refs[form].validate((valid) => {
                    if (valid) {
                        const  form = this.form;
                        //console.log(form);
                        this.addUserLoading = true
                        request.post("/system/auth/add-user",{
                            user_name:form.user,
                            mobile:form.mobile,
                            user_email:form.email,
                            user_nickname:form.nickname,
                            user_password:form.password,
                            user_status:form.status,
                            role_id:form.group,
                        }).then(response=>{
                            this.addUserLoading = false
                            let {code,data,msg}  = response
                            if(code === 0 ){
                                this.$message.success(msg);
                                this.dialogFormVisible = false
                                this.getUserList({page:1})
                                this.currentPage = 1
                                this.resetForm('form')
                            } else {
                                this.$message.error(msg);
                            }
                        }).catch(error=>{
                            console.log(error);
                        });
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            resetForm(formName) {//重置
                this.$refs[formName].resetFields();
            },
            handleEdit(index,row){      //显示编辑页面

                request.loading().get('/system/auth/edit-user',{id:row.id}).then(response=>{
                    let {code,data:{checkedRoleIds,userInfo},msg} = response
                    if(code === 0){
                        //还需获取用户的角色信息
                        let {id,user_name,mobile,user_nickname,user_status,user_email} = userInfo
                        this.currentEditData.id = id,
                        this.currentEditData.user = user_name,
                        this.currentEditData.mobile = mobile,
                        this.currentEditData.nickname = user_nickname,
                        this.currentEditData.status = user_status,
                        this.currentEditData.email = user_email,
                        this.currentEditData.password = "",
                        this.currentEditData.group_ids = checkedRoleIds
                        this.editDialog = true
                    }else {
                        this.$message.error(msg);
                    }
                })

            },
            edit(form){             //编辑提交
                this.$refs[form].validate((valid) => {
                    if (!valid) {
                        console.log('error submit!!');
                        return false;
                    }
                    let currentEditData = this.currentEditData

                    let updateData = {
                        id:currentEditData.id,
                        user_name:currentEditData.user,
                        mobile:currentEditData.mobile,
                        user_email:currentEditData.email,
                        user_nickname:currentEditData.nickname,
                        user_status:currentEditData.status,
                        role_id:currentEditData.group_ids,
                    }

                    if(currentEditData.password != ""){
                        updateData.user_password = currentEditData.password
                    }
                    this.editUserLoading = true
                    request.post("/system/auth/edit-user",updateData).then(response=>{
                        this.editUserLoading = false
                        let {code,data,msg}  = response
                        if(code === 0 ){
                            this.$message.success(msg);
                            this.editDialog = false
                            this.getUserList({page:this.currentPage})
                            this.resetForm('edit_form')
                        } else {
                            this.$message.error(msg);
                        }
                    }).catch(error=>{
                        console.log(error);
                    });
                })
            },



        }

    }
</script>
<style lang="scss" scoped>
    h1{
        text-align: center;
        margin: 30px 0;
    }
    p{
        line-height: 30px;
        margin-bottom: 10px;
        text-indent: 2em;
    }
    .logout{
        color: #409EFF;
    }
    .menu-input {
        width:300px;
        margin:0 10px;
    }

    .group-tap{
        margin-right:5px;
    }
</style>
